package com.example.android.listeners;

import java.util.ArrayList;

import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.example.android.gestures.AccRecord;
import com.example.android.gestures.Gesture;
import com.example.android.gestures.GestureParser;
import com.example.android.google.apis.R;
import com.example.android.logging.Logger;
import com.example.android.synchronization.Updater;

public class StartGestureButtonListener implements OnTouchListener
{
	SensorManager SensorManager;
	Sensor Accelerometer;

	ArrayList<AccRecord> accRecording = new ArrayList<AccRecord>();

	SensorEventListener sensorEventListener;

	public StartGestureButtonListener(
			android.hardware.SensorManager sensorManager, Sensor accelerometer)
	{
		super();
		SensorManager = sensorManager;
		Accelerometer = accelerometer;

		sensorEventListener = new AccelerometerEventListener(accRecording);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event)
	{

		if (v.getId() == R.id.startGestureButton)
		{
			if (event.getAction() == MotionEvent.ACTION_DOWN)
			{
				SensorManager.registerListener(sensorEventListener,
						Accelerometer,
						android.hardware.SensorManager.SENSOR_DELAY_FASTEST);
			} else if (event.getAction() == MotionEvent.ACTION_UP)
			{
				SensorManager.unregisterListener(sensorEventListener);

				if (accRecording.size() > 0)
				{
					Gesture gesture = GestureParser.parse(accRecording);
					Logger.makeToast(gesture.toString());
					Updater.getInstance().onGesturePerformed(gesture);
				}
					accRecording.clear();
				
			}
		}
		return false;
	}
}